package cn.school.controller.student;

import cn.hutool.core.bean.BeanUtil;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.utils.BeanUtils;
import cn.school.common.utils.SysUserUtils;
import cn.school.common.utils.poi.ExcelPoi;
import cn.school.student.entity.StudentInfo;
import cn.school.student.service.ExamResultInfoService;
import cn.school.student.service.StudentInfoService;
import cn.school.student.vo.ExamInfoVO;
import cn.school.student.vo.ExamResultPOI;
import cn.school.student.vo.ExamResultInfoVO;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@RestController
@Api(tags = "exam => 考试结果")
@RequestMapping("/exam/result")
public class ExamResultInfoController {

    @Resource
    private ExamResultInfoService examResultInfoService;

    @Resource
    StudentInfoService studentInfoService;

    @ApiOperation("分页查询列表")
    @PostMapping("/pageList")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<CommonPage<ExamResultInfoVO>> findExamResultPageList(@RequestBody ExamResultInfoVO vo){
        IPage<ExamResultInfoVO> pageList = examResultInfoService.findExamResultPageList(vo);
        return CommonResult.success(CommonPage.restPage(pageList));
    }

    @ApiOperation("新增or修改考试结果")
    @PostMapping("/edit")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<Integer> addOrUpdateExamResult(@RequestBody ExamResultInfoVO vo){
        if(vo.getExamStudents()==null || vo.getExamStudents().size()==0){
            return CommonResult.failed("缺少考试学生信息");
        }
        int num = examResultInfoService.addOrUpdateExamResult(vo);
        if(num==-1){
            return CommonResult.failed("考试成绩已经被录入，不能重复录入");
        }
        if(num>0){
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation("删除考试结果")
    @PostMapping("/delete")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<Integer> deleteResultById(@RequestBody ExamResultInfoVO vo){
        int num = examResultInfoService.deleteResultById(vo);
        if(num>0){
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation("批量删除考试结果")
    @PostMapping("/deleteBatch")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<Integer> deleteBatchExamResult(@RequestBody List<ExamResultInfoVO> list){
        int num = examResultInfoService.deleteBatchExamResult(list);
        if(num>0){
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation("批量新增考试结果")
    @PostMapping("/addBatch")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<Integer> addBatchExamResult(@RequestBody List<ExamResultInfoVO> list){
        int num = examResultInfoService.addBatchExamResult(list);
        if(num>0){
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation("查询考试信息")
    @PostMapping("/queryExam")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<List<ExamInfoVO>> queryExamByName(@RequestBody ExamInfoVO vo){
        List<ExamInfoVO> list = examResultInfoService.queryExamByName(vo);
        return CommonResult.success(list);
    }

    @ApiOperation("查询班级学生列表")
    @PostMapping("/queryClassStudents")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<List<StudentInfo>> queryClassStudents(@RequestBody ExamInfoVO vo){
        List<StudentInfo> list = examResultInfoService.queryClassStudents(vo);
        return CommonResult.success(list);
    }

    @ApiOperation("查询考试结果")
    @PostMapping("/queryExamResult")
//    @PreAuthorize("@ss.hasPermi('exam:info:list')")
    public CommonResult<List<ExamResultInfoVO>> queryExamResultList(@RequestBody ExamResultInfoVO vo){
        List<ExamResultInfoVO> list = examResultInfoService.queryExamResultList(vo.getExamId());
        return CommonResult.success(list);
    }

    @ApiOperation("导出模板")
    @GetMapping("/exportExamResultTemplateByClassId/{classId}")
    public CommonResult exportExamResultTemplateByClassId(@PathVariable("classId")Long classId, HttpServletResponse response){
        List<Long> ids = new ArrayList<>();
        ids.add(classId);
        List<StudentInfo> studentList = studentInfoService.getStudentInfosByClassIds(ids);
        List<ExamResultPOI> examResultExports = new ArrayList<>();
        for(StudentInfo student : studentList){
            ExamResultPOI examResultExport = new ExamResultPOI();
            examResultExport.setStudentName(student.getName());
            examResultExport.setStudentCode(student.getStudentId());
            examResultExports.add(examResultExport);
        }
        try {
            EasyExcel.write(response.getOutputStream(), ExamResultPOI.class).sheet(classId + " ").doWrite(examResultExports);
            return CommonResult.success();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return CommonResult.failed();
    }

    @PostMapping("/importExamResult")
    public CommonResult importExamResult(@RequestParam(value = "upload") MultipartFile upload)
    {
        try{
            if(upload == null || upload.getSize() == 0){
                return CommonResult.failed("文件为空!!!");
            }
            List<ExamResultPOI> list = new ExcelPoi<ExamResultPOI>().importObjectList(upload.getInputStream(), upload.getOriginalFilename(), ExamResultPOI.class);
            Iterator<ExamResultPOI> iterator = list.iterator();
            List<ExamResultInfoVO> resultList = new ArrayList<>();
            String username = SysUserUtils.getSysUser().getUsername();

            while (iterator.hasNext())
            {
                //excel中学生数据
                ExamResultPOI examResultImport = iterator.next();
                ExamResultInfoVO vo = new ExamResultInfoVO();
                vo.setStudentName(examResultImport.getStudentName());
                vo.setStudentCode(examResultImport.getStudentCode());
                vo.setScore(examResultImport.getScore());
                vo.setCreateBy(username);
                vo.setCreateTime(new Date());
                if("是".equals(examResultImport.getIsPass())){
                    vo.setIsPass("1");
                }else if("否".equals(examResultImport.getIsPass())) {
                    vo.setIsPass("0");
                }
                resultList.add(vo);
            }
            return CommonResult.success(resultList);
//            examResultInfoService.addBatchExamResult(resultList);
        } catch (Exception e){
            e.printStackTrace();
            return CommonResult.failed("成绩上传失败!!!");
        }
    }
}
